import type { TabItem } from '@/types/common/tab'
import router from '@/router'

export const useAppStore = defineStore('app', () => {
  const collapsed = ref(false)

  const toggleCollapsed = () => {
    collapsed.value = !collapsed.value
  }
  // 浏览过的页面,初始化时添加首页
  const cacheTabs = ref<TabItem[]>([
    {
      label: '首页',
      path: '/',
      isActive: true,
      canClose: false,
    },
  ])
  // 添加缓存页面
  const addCacheTab = (tab: TabItem) => {
    if (!cacheTabs.value.some(item => item.path === tab.path)) {
      cacheTabs.value.push(tab)
    }
    // 激活不用跳转
    activeCacheTab(tab)
  }
  // 移除缓存页面,如果当前页面是激活状态,则激活后一个页面,如果没有则激活前一个,并进行跳转
  const removeCacheTab = (tab: TabItem) => {
    const index = cacheTabs.value.findIndex(item => item.path === tab.path)
    if (index === -1) return
    const isActive = tab.isActive
    cacheTabs.value.splice(index, 1)
    if (isActive) {
      const nextTab = cacheTabs.value[index] || cacheTabs.value[index - 1]
      activeCacheTabAndJump(nextTab)
    }
  }
  // 激活缓存页面
  const activeCacheTab = (tab: TabItem) => {
    cacheTabs.value.forEach(item => {
      item.isActive = item.path === tab.path
    })
  }
  // 激活页面并跳转
  const activeCacheTabAndJump = (tab: TabItem) => {
    activeCacheTab(tab)
    router.push(tab.path)
  }

  return {
    collapsed,
    toggleCollapsed,
    cacheTabs,
    addCacheTab,
    removeCacheTab,
    activeCacheTab,
    activeCacheTabAndJump,
  }
})
